

import axios from "axios";

import {Loading,Message} from "element-ui";

import router from "@/router"
// let baseURL = "http://localhost:3000/";
let baseURL = "http://47.94.146.64:3000/"; //阿里云公网IP
// let baseURL = "http://localhost:3000/";
axios.defaults.baseURL = baseURL;



let load = null;
export function showloading() {
    load && load.close();
    load = Loading.service({
        lock: true,
        text: '请求中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}

export function showsuccess(msg) {
    load && load.close();
    Message.success({
        message: msg,
        center: true,
        duration: 1200,
        showClose: true,
    })
}

export function showerror(msg) {
    msg = msg || "请求失败";
    load && load.close();
    Message.error({
        message: msg,
        center: true,
        showClose: true,
        duration: 1200,
    })
}


// Interceptors 拦截器 
//  请求发送之前的拦截器 
axios.interceptors.request.use(function (config) {
    // 请求发送之前做的事情 

// console.log(config);
var token = sessionStorage.getItem("token");
if(token){
    config.headers['token'] = token;
}
    showloading();
    return config;
}, function (error) {
    // 请求发送失败
    showerror('请求发送失败');
    return Promise.reject(error)
})


// 响应结束之前的拦截器 
axios.interceptors.response.use(function (response) {
    // 状态码判断 
    // 打印 返回的数据 
    console.log(response.data);// axios 的数据存在data 
    // if (response.data.type) {
    //     showsuccess(response.data.msg)
    // } else {
    //     if (response.data.type == 0) {
    //         showerror(response.data.msg);
    //     } else {
    //         showsuccess(response.data.msg)
    //     }
    // }

    setTimeout(()=>{
        if(response.data.type){
            showsuccess(response.data.msg)
        }else{
            if(response.data.type==0){
                showerror(response.data.msg);
            }else{
                showsuccess(response.data.msg)
            }
        }
    },500)

    if(response.data.code == 3200){
        // router.push({name:'login'})
    }



    return response;
}, function (error) {
    //响应失败
    showerror('响应失败')
    return Promise.reject(error)
})


// promise封装axios的get请求方式
export const get = (url,params) =>{
    return new Promise(function (resolve,reject){
        axios.get(url,{
            params
        })
        .then(res=>{
            resolve(res.data)
        })
        .catch(err=>{
            reject(err)
        })
    })
}


// promise封装axios的post请求方式
export const post = (url,params) =>{
    return new Promise(function (resolve,reject){
        axios.post(url,params)
        .then(res=>{
            resolve(res.data)
        })
        .catch(err=>{
            reject(err)
        })
    })
}

export {axios,baseURL}
// export {axios}
